/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="running_task">
        <div class="table-data">
            <sf-grid>
                <sf-table
                    ref="table"
                    :options="options_fix"
                    @pagechange="_onPageChange"
                    @sizechange="_onSizeChange">
                    <sf-table-column
                        data-index="jobName"
                        :title="_('任务名称')"
                        :default-width="100">
                    </sf-table-column>
                    <template slot="jobName"
                              slot-scope="{value,record}">
                        <el-link :underline="false" type="primary" @click="toDetail(record)">{{ value }}</el-link>
                    </template>
                    <sf-table-column
                        data-index="jobStatus"
                        :default-width="100">
                        <lang>状态</lang>
                    </sf-table-column>
                    <template slot="jobStatus"
                              slot-scope="{value,record}">
                        <span :class="['table-status__'+value,'table-status__point']">{{ RUNNING_STATUS_MAP[value]
                            }}</span>
                        <span v-if="value==='queue'">( {{ record.jobInQueue }} )</span>
                    </template>
                    <sf-table-column
                        data-index="scheduleMode"
                        :default-width="100">
                        <lang>执行方式</lang>
                    </sf-table-column>
                    <template slot="scheduleMode"
                              slot-scope="{value}">
                        {{ SCHEDULE_MAP[value] }}
                    </template>
                    <sf-table-column
                        data-index="createTime"
                        :default-width="100">
                        <lang>创建时间</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="process"
                        :default-width="100">
                        <lang>任务进度</lang>
                    </sf-table-column>
                    <template slot="process"
                              slot-scope="{value, record}">
                        <div v-if="record.jobStatus !=='queue'"
                             style="height: 100%; display: flex; width: 100%; align-items: center;">
                            <sf-progress-bar
                                style="display:flex;align-items:center"
                                border-radius="10"
                                :default-height="10"
                                :default-width="140"
                                :value="value"/>
                        </div>
                        <lang v-else>等待</lang>
                    </template>
                    <sf-table-column
                        data-index="executeTime"
                        :default-width="100">
                        <lang>运行时长</lang>
                    </sf-table-column>
                    <template slot="executeTime"
                              slot-scope="{value}">
                        {{ value | secToTime }}
                    </template>
                    <sf-table-column
                        data-index="outputDataset"
                        :default-width="100">
                        <lang>输出数据集</lang>
                    </sf-table-column>
                    <template slot="outputDataset"
                              slot-scope="{value,record}">
                        <span :title="`${record.outputDataspace}/${value}`"
                              class="output__text ellipsis">{{ record.outputDataspace }}/{{ value }}</span>
                    </template>
                    <sf-table-column data-index="opr"
                                     :default-width="70">
                        <lang>操作</lang>
                    </sf-table-column>
                    <!--额外操作-->
                    <template slot="opr"
                              slot-scope="{record}">
                        <div class="table-opr">
                            <a
                                class="link-btn"
                                @click="_killTask(record)">
                                <lang>终止</lang>
                            </a>
                        </div>
                    </template>
                </sf-table>
            </sf-grid>
        </div>
    </div>
</template>

<script>
import {secToTime} from 'src/util/time'
import {TABS_MAP, SCHEDULE_MAP, RUNNING_STATUS_MAP} from "../const";


const PAGE_COUNT = 20;
const JOBS_LIST = {
    get: `/task-manage/api/v1/jobs/list`,
    kill: `/task-manage/api/v1/jobs/kill`
};
export default {
    name: "RunningTask",
    filters: {
        secToTime,
    },
    data() {
        return {
            timer: null,
            searchParams: {
                pageSize: PAGE_COUNT,
                pageNum: 0,
                plat: 0,
                history: TABS_MAP['running_task'],
            },
            options_fix: {
                bufferView: false,
                selectionHide: true,
                
                // 配置这个后才可以实现保持勾选状态
                idProperty: 'id',
                pagination: {
                    activePage: 1,
                    pageSize: PAGE_COUNT,
                    pageSizes: [Number('10'), Number('20'), Number('50')]
                }
            }
        }
    },
    
    computed: {
        SCHEDULE_MAP() {
            return SCHEDULE_MAP;
        },
        
        RUNNING_STATUS_MAP() {
            return RUNNING_STATUS_MAP;
        }
    },
    
    async mounted() {
        this.$mask();
        await this.getList();
        this.$unmask();
    },
    methods: {
        startTimer() {
            this.timer = setInterval(() => {
                this.getList();
            }, 5000);
        },
        clearTimer() {
            clearInterval(this.timer)
            this.timer = null // 如果失败则提前清除定时器
        },
        async getList() {
            let jsonData = await this.$ajax.post(JOBS_LIST.get, this.searchParams);
            let table = this.$refs.table;
            let {success, data} = jsonData;
            if (!success || !table) {
                this.clearTimer() // 如果失败则提前清除定时器
                return;
            }
            table.getPagination().setTotal(data.total);
            table.loadData(data.list || []);
            if (!this.timer) { // 如果不为空数据 则启动定时器
                this.startTimer()
            }
            
        },
        
        _onPageChange(pageNum) {
            Object.assign(this.searchParams, {
                pageNum: pageNum - 1
            });
            this.getList();
        },
        
        _onSizeChange(nowPageIndex, nowPageSize) {
            Object.assign(this.searchParams, {
                pageNum: nowPageIndex - 1,
                pageSize: nowPageSize
            });
            this.getList();
        },
        
        _killTask(record) {
            let item = record;
            let params = {};
            let title = '';
            if (item) {
                params.id = item.id;
                title = item.jobName;
            }
            
            this.$confirm({
                title: _('任务终止'),
                subTitle: _('确定要终止“{0}”任务吗？', title),
                msg: item.jobStatus === 'running' ?
                    _('任务正在进行，终止任务将会使运行进度丢失') : _('排队任务终止后可在历史任务中重新提交'),
                autoClose: true,
                callback: actionName => {
                    if (actionName === 'submit') {
                        this.ajaxKillTask(params);
                    }
                }
            });
        },
        
        async ajaxKillTask(params) {
            this.$mask();
            let jsonData = await this.$ajax.post(`${JOBS_LIST.kill}/${params.id}`, params);
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('终止失败'));
            }
            this.$ok(_('终止成功'));
            
            this.getList();
        },
        toDetail(record) {
            this.clearTimer()
            this.$router.push({
                name: 'task_detail_user',
                query: {
                    jobId: record.jobId,
                }
            })
        }
        
    },
    beforeDestroy() {
        this.clearTimer()
    }
}
</script>

<style scoped lang="less">
.running_task {
    height: 100%;
    
    .table-data {
        height: calc(100% - 41px);
        
        .sfv-grid {
            border: none;
            height: 100%;
            display: flex;
            flex-direction: column;
            
            .sfv-table {
                flex: 1;
                
                /deep/ .sfv-table_cell-center {
                    text-align: center !important;
                }
                
                /deep/ .sfv-table_cell-left {
                    text-align: left !important;
                }
                
                /deep/ .sfv-table_header-cell {
                    height: 42px;
                }
                
                /deep/ .sfv-table_header {
                    border: none;
                }
                
                /deep/ .sfv-pagination__wrapper {
                    bottom: 0;
                }
                
                /deep/ .page-size {
                    margin: -4px 8px;
                }
                
                /deep/ .sfv-progress-bar {
                    .sfv-progress-bar_text {
                        margin-left: 12px;
                    }
                }
            }
        }
    }
}
</style>
